package cn.itsource.pethome.system.shop.service.impl;

import cn.itsource.pethome.constants.BaseConstants;
import cn.itsource.pethome.jwt.LoginContextUtils;
import cn.itsource.pethome.system.employee.domain.Employee;
import cn.itsource.pethome.system.employee.mapper.EmployeeMapper;
import cn.itsource.pethome.system.shop.domain.Shop;
import cn.itsource.pethome.system.shop.domain.ShopAuditLog;
import cn.itsource.pethome.system.shop.mapper.ShopMapper;
import cn.itsource.pethome.system.shop.service.IShopAuditLogService;
import cn.itsource.pethome.base.service.impl.BaseServiceImpl;
import cn.itsource.pethome.utils.BusinessException;
import cn.itsource.pethome.utils.EmailUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author itsource
 * @since 2023-01-08
 */
@Service
public class ShopAuditLogServiceImpl extends BaseServiceImpl<ShopAuditLog> implements IShopAuditLogService {
    @Resource
    private ShopMapper shopMapper;
    @Resource
    private EmployeeMapper employeeMapper;
    @Resource
    private EmailUtil emailUtil;
    @Resource
    private LoginContextUtils loginContextUtils;

    //添加店铺日志表信息
    public void add(ShopAuditLog shopAuditLog, HttpServletRequest request) {
        //填充店铺的日志表默认数据
        shopAuditLog.setAuditTime(new Date());
        Employee employee1 = (Employee)loginContextUtils.getLoginUser(request);
        shopAuditLog.setAuditId(employee1.getId());
        //审核通过
        if (shopAuditLog.getState() == null) {
            shopAuditLog.setState(BaseConstants.Shop.STATE_WAIT_ACTIVE);//设置状态为待激活
            //添加日志并同步店铺表的状态
            Employee employee = addLog(shopAuditLog);

            //发邮件通知用户激活
            String email = employee.getEmail();
            try {
                emailUtil.complexSend(email, employee.getShop_id(),false);
            } catch (Exception e) {
                e.printStackTrace();
                throw new BusinessException("邮件发送异常，请联系管理员");
            }
        }else {//驳回
            Employee employee = addLog(shopAuditLog);
            String email = employee.getEmail();
            try {
                emailUtil.easySend(email, shopAuditLog.getNote());
            } catch (Exception e) {
                e.printStackTrace();
                throw new BusinessException("邮件发送异常，请联系管理员");
            }
        }
    }

    //添加日志，同步店铺状态。返回店铺对应的管理员信息，给他发邮件
    private Employee addLog(ShopAuditLog shopAuditLog){
        super.add(shopAuditLog);
        Shop shop = shopMapper.findOne(shopAuditLog.getShopId());
        shop.setState(shopAuditLog.getState());
        shopMapper.update(shop);
        return employeeMapper.findOne(shop.getAdminId());
    }
}
